// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

import request from '@/utils/request.js'

/**
 * 获取赛事列表
 * @returns {Promise}
 */
export function getEventList() {
  return request.get('cunba/event', {}, {
    noAuth: true,
    noVerify: true
  })
}

/**
 * 获取赛事详情
 * @param {number} eventId 赛事ID
 * @returns {Promise}
 */
export function getEventDetail(eventId) {
  return request.get(`cunba/event/${eventId}`, {}, {
    noAuth: true
  })
}

/**
 * 获取比赛列表
 * @param {Object} params 查询参数
 * @param {number} params.eventId 赛事ID（可选）
 * @param {number} params.limit 限制数量（可选）
 * @returns {Promise}
 */
export function getMatchList(params = {}) {
  return request.get('cunba/game_match', params, {
    noAuth: true,
    noVerify: true
  })
}

/**
 * 获取比赛详情
 * @param {number} matchId 比赛ID
 * @returns {Promise}
 */
export function getMatchDetail(matchId) {
  return request.get(`cunba/game_match/${matchId}`, {}, {
    noAuth: true
  })
}

/**
 * 获取球队排名
 * @param {Object} params 查询参数
 * @param {number} params.eventId 赛事ID
 * @param {number} params.groupId 分组ID
 * @param {string} params.matchType 比赛类型 (group: 小组赛, final: 决赛)
 * @returns {Promise}
 */
export function getTeamRanking(params = {}) {
  return request.get('cunba/ranking', params, {
    noAuth: true,
    noVerify: true
  })
}

/**
 * 获取球队详情
 * @param {Object} params 查询参数
 * @param {number} params.teamId 球队ID
 * @param {number} params.eventId 赛事ID
 * @returns {Promise}
 */
export function getTeamDetail(params = {}) {
  return request.get('cunba/team/detail', params, {
    noAuth: true,
    noVerify: true
  })
}

/**
 * 获取球队阵容
 * @param {number} teamId 球队ID
 * @returns {Promise}
 */
export function getTeamRoster(teamId) {
  return request.get(`cunba/team_roster/${teamId}`, {}, {
    noAuth: true
  })
}

/**
 * 获取赛程日历数据
 * @param {Object} params 查询参数
 * @param {string} params.date 日期，格式：YYYY-MM-DD (可选)
 * @param {number} params.matchType 赛事类型ID (可选)
 * @param {number} params.page 页码 (可选，默认1)
 * @param {number} params.limit 每页数量 (可选，默认20)
 * @returns {Promise}
 */
export function getCalendarData(params = {}) {
  return request.get('cunba/calendar', params, {
    noAuth: true,
    noVerify: true
  })
}

/**
 * 提交比赛预约
 * @param {Object} reservationData 预约数据
 * @param {number} reservationData.matchId 比赛ID
 * @param {string} reservationData.name 预约人姓名
 * @param {string} reservationData.idCard 身份证号
 * @param {string} reservationData.phone 手机号
 * @returns {Promise}
 */
export function submitReservation(reservationData) {
  return request.post('cunba/reservation', reservationData, {
    noAuth: false
  })
}

/**
 * 获取预约详情
 * @param {string} reservationCode 预约编号
 * @returns {Promise}
 */
export function getReservationDetail(reservationCode) {
  return request.get(`cunba/reservation/${reservationCode}`, {}, {
    noAuth: false
  })
}

/**
 * 取消预约
 * @param {string} reservationCode 预约编号
 * @returns {Promise}
 */
export function cancelReservation(reservationCode) {
  return request.delete(`cunba/reservation/${reservationCode}`, {}, {
    noAuth: false
  })
}

/**
 * 获取用户预约列表
 * @param {Object} params 查询参数
 * @param {number} params.page 页码
 * @param {number} params.limit 每页数量
 * @param {string} params.status 预约状态（可选）
 * @returns {Promise}
 */
export function getUserReservations(params = {}) {
  return request.get('cunba/user/reservations', params, {
    noAuth: false
  })
}

// 工具函数

/**
 * iOS兼容的日期解析函数
 * @param {string} dateString 日期字符串
 * @returns {Date} 解析后的日期对象
 */
function parseCompatibleDate(dateString) {
  if (!dateString) return new Date()
  
  // 将 "YYYY-MM-DD HH:mm:ss" 格式转换为 "YYYY/MM/DD HH:mm:ss"
  // iOS更兼容这种格式
  if (typeof dateString === 'string') {
    const formattedDate = dateString.replace(/-/g, '/')
    return new Date(formattedDate)
  }
  
  return new Date(dateString)
}

/**
 * 格式化比赛时间
 * @param {string} matchTime 比赛时间字符串
 * @returns {Object} 格式化后的时间信息
 */
export function formatMatchTime(matchTime) {
  try {
    const now = new Date()
    const match = parseCompatibleDate(matchTime)
    
    // 检查日期是否有效
    if (isNaN(match.getTime())) {
      console.warn('无效的比赛时间格式:', matchTime)
      return {
        timeLabel: '时间待定',
        timeDisplay: '--:--'
      }
    }
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000)
    const matchDate = new Date(match.getFullYear(), match.getMonth(), match.getDate())
    
    let timeLabel = ''
    
    if (matchDate.getTime() === today.getTime()) {
      timeLabel = '今天'
    } else if (matchDate.getTime() === tomorrow.getTime()) {
      timeLabel = '明天'
    } else {
      timeLabel = `${match.getMonth() + 1}月${match.getDate()}日`
    }
    
    const hours = match.getHours().toString().padStart(2, '0')
    const minutes = match.getMinutes().toString().padStart(2, '0')
    
    return {
      timeLabel: timeLabel,
      timeDisplay: `${hours}:${minutes}`,
      fullDateTime: match,
      isToday: matchDate.getTime() === today.getTime(),
      isTomorrow: matchDate.getTime() === tomorrow.getTime()
    }
  } catch (error) {
    console.error('比赛时间格式化失败:', matchTime, error)
    return {
      timeLabel: '时间待定',
      timeDisplay: '--:--',
      fullDateTime: new Date(),
      isToday: false,
      isTomorrow: false
    }
  }
}

/**
 * 获取比赛状态文本
 * @param {number} status 状态码
 * @param {string} matchTime 比赛时间
 * @returns {string} 状态文本
 */
export function getMatchStatusText(status, matchTime) {
  try {
    const now = new Date()
    const match = parseCompatibleDate(matchTime)
    
    // 检查日期是否有效
    if (isNaN(match.getTime())) {
      console.warn('无效的比赛时间格式:', matchTime)
      return '时间待定'
    }
  
    if (match.getTime() > now.getTime()) {
      return '未开始'
    } else if (status === 2) {
      return '进行中'
    } else if (status === 1 || status === 3) {
      return '已结束'
    } else {
      return '未开始'
    }
  } catch (error) {
    console.error('比赛状态获取失败:', matchTime, error)
    return '时间待定'
  }
}

/**
 * 获取观看类型
 * @param {number} status 比赛状态
 * @param {string} matchTime 比赛时间
 * @returns {string} 观看类型
 */
export function getWatchType(status, matchTime) {
  try {
    const now = new Date()
    const match = parseCompatibleDate(matchTime)
    
    // 检查日期是否有效
    if (isNaN(match.getTime())) {
      console.warn('无效的比赛时间格式:', matchTime)
      return '预约'
    }
  
    if (match.getTime() > now.getTime()) {
      return '预约'
    } else if (status === 2) {
      return '免费观'
    } else if (status === 1 || status === 3) {
      return '回放'
    } else {
      return '免费观'
    }
  } catch (error) {
    console.error('观看类型获取失败:', matchTime, error)
    return '预约'
  }
}

/**
 * 格式化球队数据
 * @param {Object} teamData 原始球队数据
 * @returns {Object} 格式化后的球队数据
 */
export function formatTeamData(teamData) {
  return {
    id: teamData.team_id || teamData.id,
    name: teamData.team_name || teamData.name,
    logo: teamData.logo || '/static/images/team.png',
    wins: teamData.win || 0,
    losses: teamData.lose || 0,
    points: (teamData.win || 0) * 2, // 简单积分计算
    rank: teamData.rank || '--'
  }
}

/**
 * 格式化比赛数据
 * @param {Object} matchData 原始比赛数据
 * @returns {Object} 格式化后的比赛数据
 */
export function formatMatchData(matchData) {
  // 兼容不同接口的时间字段
  const matchTime = matchData.match_time || matchData.matchTime || matchData.time || matchData.startTime || matchData.date
  const timeInfo = formatMatchTime(matchTime)
  const statusText = getMatchStatusText(matchData.status, matchTime)
  const watchType = getWatchType(matchData.status, matchTime)
  
  return {
    id: matchData.id,
    time: timeInfo.timeDisplay, // 显示具体时间如 "14:30"
    matchTime: matchTime, // 保留原始时间数据
    timeLabel: timeInfo.timeLabel, // 显示"今天"、"明天"等
    dateType: matchData.dateType, // 保留日期类型标记
    originalDate: matchData.originalDate, // 保留原始日期
    homeTeam: {
      id: matchData.team1_id || matchData.homeTeamId || matchData.home_team_id,
      name: matchData.team1_name || matchData.homeTeamName || matchData.home_team_name || matchData.homeTeam?.name || '主队',
      logo: matchData.team1_logo || matchData.home_team_logo || matchData.homeTeam?.logo || '/static/images/team_selected.png'
    },
    awayTeam: {
      id: matchData.team2_id || matchData.awayTeamId || matchData.away_team_id,
      name: matchData.team2_name || matchData.awayTeamName || matchData.away_team_name || matchData.awayTeam?.name || '客队',
      logo: matchData.team2_logo || matchData.away_team_logo || matchData.awayTeam?.logo || '/static/images/team_selected.png'
    },
    status: statusText,
    watchType: watchType,
    watchInfo: {
      type: watchType === '免费观' ? 'free' : (watchType === '预约' ? 'reservation' : 'paid')
    },
    score1: matchData.score1 || 0,
    score2: matchData.score2 || 0,
    location: matchData.location || matchData.venue,
    remark: matchData.remark || matchData.description,
    eventId: matchData.event_id || matchData.eventId
  }
}
